import requests
from django_redis import get_redis_connection
from datetime import datetime
from user.models import UserProfile
from apikey.models import AllowModel


def reset(user: UserProfile, type_):
    for item in AllowModel.objects.all():
        user.count[item] = getattr(AllowModel, type_)


def reset_count_task():
    user_all = UserProfile.objects.all()
    for user in user_all:
        BillingType = int(user.billing_type)
        MemberType = int(user.membership_type)
        Expired = user.expired
        if BillingType == 1 and MemberType == 1:
            reset(user, "OrdinaryMemberCount")
        elif BillingType == 1 and MemberType == 2 and Expired > datetime.now():
            reset(user, "PremiumMemberCount")
        elif BillingType == 1 and MemberType == 2 and Expired <= datetime.now():
            reset(user, "OrdinaryMemberCount")
            user.membership_type = 1
        elif BillingType == 1 and MemberType == 3 and Expired <= datetime.now():
            reset(user, "OrdinaryMemberCount")
            user.membership_type = 1
        elif BillingType == 1 and MemberType == 3 and Expired > datetime.now():
            reset(user, "AnnualMemberCount")
        elif BillingType == 2 and user.gpt3_count == 0:
            reset(user, "OrdinaryMemberCount")
            user.membership_type = 1
            user.billing_type = 1
        user.save()


def bing_wallpapers():
    try:
        proxies = {
            'http': 'http://127.0.0.1:7890',
            'https': 'http://127.0.0.1:7890',
        }
        url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=8&mkt=zh-CN'
        response = requests.get(url, proxies=proxies)
        images = response.json().get('images')
        r = get_redis_connection('bing_wallpapers')
        r.flushdb()
        pipeline = r.pipeline()
        for index, item in enumerate(images):
            pipeline.set(index, f"https://www.bing.com{item['url']}")
        pipeline.execute()
        print('获取壁纸完成')
    except Exception as e:
        print(e.__traceback__.tb_lineno)
        print(e)
